package com.lan;


import com.lan.antlr.ScriptLexer;
import com.lan.antlr.ScriptParser;
import com.lan.parse.ParseJslListener;
import com.lan.parse.TestScriptBaseListener;
import com.lan.parse.VarListener;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

public class ScriptCompiler {

    private ScriptContext context;

    private ScriptLexer lexer;

    private ScriptParser parser;

    public ScriptContext compile(String script) {
        context = new ScriptContext();
        //词法分析
        lexer = new ScriptLexer(CharStreams.fromString(script));
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        //语法分析
        parser = new ScriptParser(tokens);
        context.setAst(parser.prog());

//        parser.addErrorListener(new ANTLRErrorListener() {
//
//
//            @Override
//            public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
//                System.out.println(msg);
//                System.out.println(e.getMessage());
//            }
//
//            @Override
//            public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact, BitSet ambigAlts, ATNConfigSet configs) {
//                System.out.println("reportAmbiguity");
//            }
//
//            @Override
//            public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet conflictingAlts, ATNConfigSet configs) {
//                System.out.println("reportAttemptingFullContext");
//            }
//
//            @Override
//            public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, int prediction, ATNConfigSet configs) {
//                System.out.println("reportContextSensitivity");
//            }
//        });
        //语义分析
        ParseTreeWalker walker = new ParseTreeWalker();

        //多步的语义解析。
        //优点：1.代码更清晰；2.允许使用在声明之前，这在支持面向对象、递归函数等特征时是必须的。
        //pass1：类型和Scope
//        TestScriptBaseListener pass1 = new TestScriptBaseListener(context);
//        walker.walk(pass1, context.getAst());

//        TestScriptBaseListener scopeScanner = new TestScriptBaseListener(context);
//        walker.walk(scopeScanner, context.getAst());
        ParseJslListener parseJslListener = new ParseJslListener(context);
        walker.walk(parseJslListener, context.getAst());


        VarListener varListener = new VarListener(context);
        walker.walk(varListener, context.getAst());
        return context;
    }


}
